/**
 * Created by dmrj on 2016/5/5.
 */
define(['jquery', 'appLocalStorage', 'appConst', 'model/global', 'appMessageBox', 'business/project/projectConfig', 'jeditable/jquery.jeditable',
    'jquery-form/jquery-form.min'], function ($, appLocalStorage, appConst, global, msgBox, projectConfig) {

    var MAX_LENGTH = 100;
    var that;
    var components = {};
    var data = {
        code: $("#code").val().trim(),
        name: $("#name").val().trim()
    };

    return {
        init: function () {
            that = this;
            components = {
                "form_pdetail_project": $("#project-form"),
                "form_pdetail_psa": $("#psa-form"),
                "radio_pdetail_form1": $("#radio-form1"),
                "radio_pdetail_form2": $("#radio-form2"),
                "radio_pdetail_psa": $("#psa-form"),
                "input_pid": $('#p_id'),
                "input_pdetail_code": $("#code"),
                "input_pdetail_name": $("#name"),
                "input_pdetail_description": $("#description"),
                "input_pdetail_projectColumn": $("#input_addPSA"),
                "input_pdetail_dcgroupvalue": $("#dcgroupvalue"),
                "input_pdetail_ccgroupvalue": $("#ccgroupvalue"),
                "radio_pdetail_ccRadio": $("#ccRadio"),
                "radio_pdetail_dcRadio": $("#dcRadio"),
                "radio_pdetail_default1": $(".default1"),
                "radio_pdetail_default2": $(".default2"),
                "radio_pdetail_customGroup1": $(".customGroup1"),
                "radio_pdetail_customGroup2": $(".customGroup2"),
                "a_pdetail_dcSave": $("#dcSave"),
                "a_pdetail_ccSave": $("#ccSave"),
                "btn_pdetail_attributeSubmit": $("#attributeSubmit"),
                "tbl_cpw": $('#dt_cpw'),
                "tbl_ccw": $("#dt_ccw"),
                "tbl_psa": $("#dt_psa"),
                hid_grr_defaultValue: $("#hid_grr_defaultValue"),
                slt_project_grr_type: $('#slt_project_grr_type'),
                slt_project_grr_sigma: $('#slt_project_grr_sigma'),
                txt_project_grr_part: $("#txt_project_grr_part"),
                txt_project_grr_operator: $("#txt_project_grr_operator"),
                txt_project_grr_trial: $("#txt_project_grr_trial"),
                form_grr_setting: $("#form_grr_setting"),
                btn_project_grr_save: $("#btn_project_grr_save"),

                txt_project_psgrr_id: $("#txt_project_psgrr_id"),
                txt_project_psgrr_model: $("#txt_project_psgrr_model"),
                txt_project_psgrr_sigma: $("#txt_project_psgrr_sigma"),
                txt_project_psgrr_rules: $("#txt_project_psgrr_rules"),
                txt_project_psgrr_defaultModelValue: $("#txt_project_psgrr_defaultModelValue"),
                txt_project_grr_Excellent: $("#txt_project_grr_Excellent"),
                txt_project_grr_Adequate: $("#txt_project_grr_Adequate"),
                txt_project_grr_Marginal: $("#txt_project_grr_Marginal")
            };

            that.initValidateRule();
            that.formValidate();
            that.initStatisticAnalysisParameter();
            that.initCpwTable();
            that.initCcwTable();
            that.initPsaTable();

            that.initEventClick();
            that.initGrrSetting();
            that.submitGrrSetting();
        },

        initValidateRule: function () {
            projectConfig.positiveInt();
            projectConfig.excellentRuleCheck();
            projectConfig.betweenRuleCheck();
            projectConfig.marginalRuleCheck();
        },
        formValidate: function () {
            components.form_pdetail_project.validate({
                rules: {
                    code: {
                        required: true,
                        keyContainBlankCheck: true,
                        remote: {
                            type: "POST",
                            url: "project/checkNameOrCode",
                            dataType: 'json',
                            data: {
                                projectCode: function () {
                                    return components.input_pdetail_code.val().trim();
                                },
                                projectId: function () {
                                    return components.input_pid.val().trim();
                                }
                            }
                        }
                    },
                    name: {
                        required: true,
                        keyContainBlankCheck: true,
                        remote: {
                            type: "POST",
                            url: "project/checkNameOrCode",
                            dataType: 'json',
                            data: {
                                projectName: function () {
                                    return components.input_pdetail_name.val().trim();
                                },
                                projectId: function () {
                                    return components.input_pid.val().trim();
                                }
                            }
                        }
                    }
                },
                messages: {
                    code: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('PROJECT_CODE')),
                        remote: $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS", $.i18n.prop('PROJECT_CODE')),
                    },
                    name: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('PROJECT_NAME')),
                        remote: $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS", $.i18n.prop('PROJECT_NAME')),
                    }
                },

                submitHandler: function (form) {
                    appLocalStorage.setLocal("ispc.search.project.code." + global.getUserId(), components.input_pdetail_code.val().trim());
                    $(form).ajaxSubmit({
                        success: function (d) {
                            if (d.code == 0) {
                                msgBox.errorBox(d.message, 'MENU_PROJECT');
                                return false;
                            }

                            if (d.code == 1) {
                                msgBox.successBox({
                                    title: $.i18n.prop("MESSAGEBOX_TITLE_TIPS"),
                                    content: $.i18n.prop("PROJECT_SAVE_SUCCESS")
                                });
                            }
                        },
                        error: function (e) {
                            if (e.status == 401) {
                                msgBox.sessionFailureBox();
                            }
                            if (e.status == 500) {
                                msgBox.serverFailureBox();
                            }
                            if (e.status == 404) {
                                msgBox.pathFailureBox();
                            }
                        }
                    });
                },
                errorPlacement: function (error, element) {
                    error.insertAfter(element.parent());
                }
            });
        },
        checkPsaAttribute: function () {
            var $validator = components.form_pdetail_psa.validate({
                rules: {
                    value: {
                        required: true,
                        keyContainBlankCheck: true
                    }
                },
                messages: {
                    value: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('ATTRIBUTE_PROJECT_ATTRIBUTE'))
                    }
                }
            });

            var $valid = components.form_pdetail_psa.valid();
            if (!$valid) {
                $validator.focusInvalid();
                return false;
            }
            return true;
        },
        initEventClick: function () {
            components.input_pdetail_projectColumn.click(function () {
                $(this).val("");
            });

            components.btn_pdetail_attributeSubmit.click(function () {
                if (that.checkPsaAttribute()) {
                    that.addPSA();
                }
            });

            components.radio_pdetail_default1.click(function () {
                components.input_pdetail_dcgroupvalue.val("");
                components.input_pdetail_dcgroupvalue.attr("disabled", "disabled");

                if (components.input_pdetail_dcgroupvalue.parent().hasClass("state-error")) {

                    components.input_pdetail_dcgroupvalue.parent().removeClass("state-error");
                    components.input_pdetail_dcgroupvalue.next().remove();
                }

                components.input_pdetail_dcgroupvalue.parent().removeClass("state-success");
            });

            components.radio_pdetail_default2.click(function () {
                components.input_pdetail_ccgroupvalue.val("");
                components.input_pdetail_ccgroupvalue.attr("disabled", "disabled");

                if (components.input_pdetail_ccgroupvalue.parent().hasClass("state-error")) {

                    components.input_pdetail_ccgroupvalue.parent().removeClass("state-error");
                    components.input_pdetail_ccgroupvalue.next().remove();
                }
                components.input_pdetail_ccgroupvalue.parent().removeClass("state-error");
                components.input_pdetail_ccgroupvalue.parent().removeClass("state-success");
            });

            components.radio_pdetail_customGroup2.click(function () {
                components.input_pdetail_ccgroupvalue.removeAttrs("disabled");
                components.input_pdetail_ccgroupvalue.focus();
            });

            components.radio_pdetail_customGroup1.click(function () {
                components.input_pdetail_dcgroupvalue.removeAttrs("disabled");
                components.input_pdetail_dcgroupvalue.focus();
            });
        },
        initCpwTable: function () {
            components.tbl_cpw.dataTable({
                "sDom": "<'row'<'col-sm-12' t>> <'row'<'col-sm-5' i><'col-sm-7' p>>",
                "searching": false,
                "autoWidth": false,
                "stateSave": true,
                "ordering": false,
                "paging": true,
                "language": appConst.table_language(),
                "serverSide": true,
                "ajax": {
                    "url": 'project/cpw',
                    "type": "POST",
                    "dataSrc": "body",
                    "traditional": true,
                    "data": {'id': components.input_pid.val()},
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "id"},
                    {"data": "indiceName"},
                    {"data": "excellentBoundaryValue"},
                    {"data": "goodBoundaryValue"},
                    {"data": "acceptableBoundaryValue"},
                    {"data": "rectificationBoundaryValue"}
                ],
                "columnDefs": [
                    {
                        "targets": [1],
                        "visible": false
                    },
                    {
                        "targets": [2],
                        "render": function (data, type, full) {
                            if (data == 'CA') {
                                return data + " (%)"
                            }
                            return data;
                        }
                    },
                    {
                        "targets": [3],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'excellentBoundaryValue').attr('dataId', rowData.id).attr('row', row).attr('col', col);       //.attr('data-code', 'td_excellentBoundaryValue_' + rowData.id + '_' + row + '_' + col);
                        }
                    }, {
                        "targets": [4],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'goodBoundaryValue').attr('dataId', rowData.id).attr('row', row).attr('col', col);
                        }
                    }, {
                        "targets": [5],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'acceptableBoundaryValue').attr('dataId', rowData.id).attr('row', row).attr('col', col);
                        }
                    }, {
                        "targets": [6],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'rectificationBoundaryValue').attr('dataId', rowData.id).attr('row', row).attr('col', col);
                        }
                    }
                ],
                "drawCallback": function (settings) {
                    var api = this.api();
                    $('#dt_cpw tbody td.inputTd').jeditable(function (value, settings) {
                        var cell = api.cell(this);
                        cell.data(value);

                        var row = parseInt($(this).attr('row')) + 1;
                        var cell = parseInt($(this).attr('col'));
                        var name = $(this).attr('type');
                        var value = value;
                        var id = parseInt($(this).attr('dataId'));

                        var tel = /^[a-zA-Z0-9.]+$/;
                        if (isNaN(value) == true || !tel.test(value)) {
                            value = "";
                        }

                        if (value.length > MAX_LENGTH) {
                            $(this).addClass("tableDataError");
                            settings.placeholder = $.i18n.prop("MESSAGE_VALIDATE_LENGTH", $.i18n.prop("GLOBAL_FIELD_MAX"));
                            return false;
                        } else {
                            $(this).removeClass("tableDataError");
                        }

                        if (value == "") {
                            $(this).addClass("tableDataError");
                            settings.placeholder = $.i18n.prop("VALIDATE_CCW");
                            return false;
                        } else {
                            $(this).removeClass("tableDataError");
                        }
                        var obj = {
                            id: id
                        };

                        if (name == 'excellentBoundaryValue') {
                            var value1 = components.tbl_cpw.find("tr").eq(row).find("td").eq(cell).text();
                            if (row == 1 && parseFloat(value) > parseFloat(value1)) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_NEXT");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                            if (row != 1 && parseFloat(value) < parseFloat(value1)) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_NEXT");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                            obj.excellentBoundaryValue = value;
                        }

                        if (name == 'goodBoundaryValue') {
                            var value1 = components.tbl_cpw.find("tr").eq(row).find("td").eq(cell - 2).text();
                            var value2 = components.tbl_cpw.find("tr").eq(row).find("td").eq(cell).text();
                            if (row == 1 && (parseFloat(value) < parseFloat(value1))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_PREVIOUS");
                                return false;
                            } else if (row == 1 && (parseFloat(value2) < parseFloat(value))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_NEXT");
                                return false;
                            }
                            else {
                                $(this).removeClass("tableDataError");
                            }
                            if (row != 1 && (parseFloat(value) > parseFloat(value1))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_PREVIOUS");
                                return false;
                            } else if (row != 1 && (parseFloat(value2) > parseFloat(value))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_NEXT");
                                return false;
                            }
                            else {
                                $(this).removeClass("tableDataError");
                            }
                            obj.goodBoundaryValue = value;
                        }

                        if (name == 'acceptableBoundaryValue') {
                            var value1 = components.tbl_cpw.find("tr").eq(row).find("td").eq(cell - 2).text();
                            var value2 = components.tbl_cpw.find("tr").eq(row).find("td").eq(cell).text();
                            if (row == 1 && (parseFloat(value) < parseFloat(value1))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_PREVIOUS");
                                return false;
                            } else if (row == 1 && (parseFloat(value2) < parseFloat(value))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_NEXT");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                            if (row != 1 && (parseFloat(value) > parseFloat(value1))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_PREVIOUS");
                                return false;
                            } else if (row != 1 && (parseFloat(value2) > parseFloat(value))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_NEXT");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                            obj.acceptableBoundaryValue = value;
                        }

                        if (name == 'rectificationBoundaryValue') {
                            var value1 = components.tbl_cpw.find("tr").eq(row).find("td").eq(cell - 2).text();
                            if (row == 1 && parseFloat(value) < parseFloat(value1)) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_PREVIOUS");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                            if (row != 1 && parseFloat(value) > parseFloat(value1)) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_PREVIOUS");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                            obj.rectificationBoundaryValue = value;
                        }

                        var array = new Array();
                        array.push(obj);
                        that.submitAjaxData("project/updateCPW", array);
                    }, {
                        height: '20',
                        width: '200',
                        cssclass: 'smart-form'
                    });
                }
            });
            components.tbl_cpw.dataTable().on('draw.dt', function () {
                var dt = $(this).dataTable();
                dt.api().column(0, {draw: 'applied'}).nodes().each(function (cell, i) {
                    var pageNum = dt.api().page();
                    var pageSize = dt.api().page.len();
                    cell.innerHTML = pageNum * pageSize + i + 1;
                });
            });
        },
        initCcwTable: function () {
            components.tbl_ccw.dataTable({
                "sDom": "<'row'<'col-sm-12' t>> <'row'<'col-sm-5' i><'col-sm-7' p>>",
                "paging": true,
                "autoWidth": false,
                "stateSave": true,
                "language": appConst.table_language(),
                "ordering": false,
                "serverSide": true,
                "ajax": {
                    "url": 'project/ccw',
                    "type": "POST",
                    "dataSrc": "body",
                    "traditional": true,
                    "data": {'id': components.input_pid.val()},
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "code"},
                    {"data": "isVisible"},
                    {"data": "detailRule"},
                    {"data": "points"},
                    {"data": "somePoints"},
                    {"data": "sigma"},
                ],
                "columnDefs": [
                    {
                        "targets": [2],
                        "render": function (data, type, full) {
                            var result = "";
                            if (data == true) {
                                result = "YES";
                            } else if (data == false) {
                                result = "NO";
                            }
                            return result;
                        },
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('selctTd').attr('data-code', 'td_isVisible' + '_' + rowData.id)
                        }
                    }, {
                        "targets": [4],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'points').attr('dataId', rowData.id);
                        }
                    }, {
                        "targets": [5],
                        "render": function (data, type, full) {
                            var result = "";
                            if (full.code == "R5" || full.code == "R6") {
                                result = data;
                            } else {
                                result = "--";
                            }
                            return result;
                        },
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'somePoints').attr('dataId', rowData.id);
                            if (row != 4 && row != 5) {
                                $(td).removeClass('inputTd');
                                $(td).attr('style', 'color:#C0C0C0');
                            }
                        }
                    }, {
                        "targets": [6],
                        "render": function (data, type, full) {
                            var result = "";
                            if (full.code == "R2" || full.code == "R3" || full.code == "R4") {
                                result = "--";
                            } else {
                                result = data;
                            }
                            return result;
                        },
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'sigma').attr('dataId', rowData.id);
                            if (row > 0 && row < 4) {
                                $(td).removeClass('inputTd');
                                $(td).attr('style', 'color:#C0C0C0');
                            }
                        }
                    }
                ],
                "drawCallback": function (settings) {
                    var api = this.api();
                    $('#dt_ccw tbody td.inputTd').jeditable(function (value, settings) {
                        var cell = api.cell(this);
                        cell.data(value);
                        var id = $(this).attr('dataId');
                        var name = $(this).attr('type');
                        var value = value;

                        var tel = /^[a-zA-Z0-9.]+$/;
                        if (isNaN(value) == true || !tel.test(value)) {
                            value = "";
                        }

                        if (value.length > MAX_LENGTH) {
                            $(this).addClass("tableDataError");
                            settings.placeholder = $.i18n.prop("MESSAGE_VALIDATE_LENGTH", $.i18n.prop("GLOBAL_FIELD_MAX"));
                            return false;
                        } else {
                            $(this).removeClass("tableDataError");
                        }

                        if (value == "") {
                            $(this).addClass("tableDataError");
                            settings.placeholder = $.i18n.prop("VALIDATE_CCW");
                            return false;
                        } else {
                            $(this).removeClass("tableDataError");
                        }
                        var obj = {
                            id: id
                        };

                        if (name == 'isVisible') {
                            obj.isVisible = value;
                        }

                        if (name == 'points') {
                            obj.points = value;
                        }

                        if (name == 'somePoints') {
                            obj.somePoints = value;
                        }

                        if (name == 'sigma') {
                            obj.sigma = value;
                        }

                        var array = new Array();
                        array.push(obj);
                        that.submitAjaxData("project/updateCCW", array);
                    }, {
                        height: '20',
                        width: '100',
                        cssclass: 'smart-form',
                        placeholder: $.i18n.prop("VALIDATE_CCW")
                    });
                    $('#dt_ccw tbody td.selctTd').jeditable(function (value, settings) {
                            var cell = api.cell(this);
                            cell.data(value);
                            $(this).html(cell.data());
                            var code;

                            if (cell.data() == 'NO') {
                                code = $(this).attr('data-code') + '_' + false;
                            }
                            else {
                                code = $(this).attr('data-code') + '_' + true;
                            }

                            $(this).attr('data-code', code);
                            var arr = $(this).attr('data-code').split('_');
                            var id = arr[2];
                            var name = arr[1];
                            var value = arr[3];
                            var obj = {
                                id: id
                            };

                            if (name == 'isVisible') {
                                obj.isVisible = value;
                            }

                            var array = new Array();
                            array.push(obj);
                            that.submitAjaxData("project/updateCCW", array);
                        }, {
                            type: 'select',
                            submit: $.i18n.prop('GLOBAL_BUTTON_OK'),
                            data: {"YES": "YES", "NO": "NO"}
                        }
                    );
                }
            });

            components.tbl_ccw.dataTable().on('draw.dt', function () {
                var dt = $(this).dataTable();
                dt.api().column(0, {draw: 'applied'}).nodes().each(function (cell, i) {
                    var pageNum = dt.api().page();
                    var pageSize = dt.api().page.len();
                    cell.innerHTML = pageNum * pageSize + i + 1;
                });
            });
        },
        initPsaTable: function () {
            components.tbl_psa.dataTable({
                "sDom": "<'row'<'col-sm-12' t>> <'row'<'col-sm-5' i><'col-sm-7' p>>",
                "paging": false,
                "autoWidth": false,
                "stateSave": true,
                "language": appConst.table_language(),
                "ordering": false,
                "serverSide": true,
                "ajax": {
                    "url": 'project/psa',
                    "type": "POST",
                    "dataSrc": "body",
                    "traditional": true,
                    "data": {'id': components.input_pid.val()},
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "name"},
                    {"data": "value"},
                    {"data": "isDefault"},
                    {"data": "isDefault"},
                    {"data": "isShow"}
                ],
                "columnDefs": [
                    {
                        "targets": [2],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('data-code', 'td_value' + '_' + rowData.id + '_' + rowData.isDefault + "_" + rowData.project.id);
                        }
                    },
                    {
                        "targets": [3],
                        "visible": false,
                        "render": function (data, type, full) {
                            var result = "";
                            if (data == true) {
                                result = "YES";
                            } else if (data == false) {
                                result = "NO";
                            }
                            return result;
                        }
                    },
                    {
                        "targets": [4],
                        "render": function (data, type, full) {
                            var id = full.id;
                            var operate = "";
                            if (data == true) {
                                operate = "<div class='center'></div>"
                            } else if (data == false) {
                                operate = "<div class='center'><a href='javascript:void(0);' class='deletePSAConfirmdd' id='" + id + "'>Delete</a></div>";    //onclick='deletePSA(" + id + ")'
                            }
                            return operate;
                        }
                    },
                    {
                        "targets": [5],
                        "render": function (data, type, full) {
                            var id = full.id;
                            var operate = "";
                            var code = full.id + '_' + full.isDefault;
                            var v = full.value;
                            if (data == true) {
                                operate = "<input type='checkbox' name='checkbox' id='" + v + "'value=" + code + " checked='checked'/>";
                            } else if (data == false) {
                                operate = "<input type='checkbox' id='" + v + "' value=" + code + " name='checkbox'/>";
                            }
                            return operate;
                        }
                    }
                ],
                "drawCallback": function (settings) {
                    var api = this.api();
                    $('#dt_psa tbody td.inputTd').jeditable(
                        function (value, settings) {
                            var cell = api.cell(this);
                            cell.data(value);
                            var code = $(this).attr('data-code');
                            var arr = code.split('_');
                            var id = arr[2];
                            var name = arr[1];
                            var isDefault = arr[3];
                            var projectId = arr[4];
                            var value = cell.data().trim();
                            if (value == "") {
                                $(this).addClass("tableDataError");
                                return false;
                            }
                            else {
                                $(this).removeClass("tableDataError");
                            }
                            var obj = {
                                "id": id,
                                "project": {id: projectId},
                                "isDefault": isDefault
                            };
                            if (name == 'value') {
                                obj.value = value;
                            }

                            that.submitAjaxData("project/updatePSA", obj);
                        }, {
                            height: '20',
                            width: '300',
                            cssclass: 'smart-form',
                            placeholder: $.i18n.prop("VALIDATE_ATTRIBUTE")
                        });
                    components.tbl_psa.find(".deletePSAConfirmdd").unbind("click").on("click", function () {
                        that.deletePSA($(this).attr("id"));
                    });
                }

            });

            components.tbl_psa.on('click', 'tr input[name="checkbox"]', function () {
                var code = $(this).attr('value');
                var arr = code.split('_');
                var id = arr[0];
                var name = arr[1];
                var value = $(this).attr('id');
                var isDefault = arr[1];
                var projectId = arr[4];
                var show = false;

                if ($(this).is(':checked')) {
                    show = true;
                } else {
                    show = false;
                }
                var obj = {
                    "id": id,
                    "name": name,
                    "value": value,
                    "isDefault": isDefault,
                    "project": {id: projectId},
                    "isShow": show
                };
                that.submitAjaxData("project/updatePSA", obj);
            });

            components.tbl_psa.dataTable().on('draw.dt', function () {
                var dt = $(this).dataTable();
                dt.api().column(0, {draw: 'applied'}).nodes().each(function (cell, i) {
                    cell.innerHTML = i + 1;
                });
            });
        },
        initStatisticAnalysisParameter: function () {

            var ccValue;
            var dcValue;
            var analysisParameterId;

            $.ajax({
                url: "project/findStatisticAnalysisParameter",
                type: "POST",
                dataType: "json",
                data: "id=" + components.input_pid.val(),
                success: function (data) {
                    analysisParameterId = data.body.id;
                    if (data.body.distributionChartGroupingNumber != null) {

                        dcValue = data.body.distributionChartGroupingNumber;
                        components.input_pdetail_dcgroupvalue.val(dcValue);

                        $('input[name=group_dc]').each(function () {
                            $(this).removeAttr('checked');
                        });
                        components.radio_pdetail_dcRadio.prop('checked', true);
                    }
                    else {
                        components.input_pdetail_dcgroupvalue.attr("disabled", "disabled");
                    }

                    if (data.body.controlChartGroupingNumber != null) {
                        ccValue = data.body.controlChartGroupingNumber;
                        components.input_pdetail_ccgroupvalue.val(ccValue);

                        $('input[name=cc_group]').each(function () {
                            $(this).removeAttr('checked');
                        });
                        components.radio_pdetail_ccRadio.prop('checked', true);
                    }
                    else {
                        components.input_pdetail_ccgroupvalue.attr("disabled", "disabled");
                    }
                },
                error: function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });

            components.a_pdetail_dcSave.click(function () {
                var controlChartGroupingNumber = parseInt(components.input_pdetail_ccgroupvalue.val().trim());
                var number;
                if ($("input[name='group_dc']").eq(0).prop("checked")) {
                    number = undefined;
                }
                else {
                    number = parseInt(components.input_pdetail_dcgroupvalue.val().trim());
                }

                var obj = {
                    id: analysisParameterId,
                    distributionChartGroupingNumber: number,
                    controlChartGroupingNumber: controlChartGroupingNumber
                };
                var arr = new Array();
                arr.push(obj);

                that.submitRadio("DC", number, arr, "project/updataDcGroupNumber");
            });

            components.a_pdetail_ccSave.click(function () {

                var distributionChartGroupingNumber = parseInt(components.input_pdetail_dcgroupvalue.val());
                var number;
                if ($("input[name='group_cc']").eq(0).prop("checked")) {
                    number = undefined;
                }
                else {
                    number = parseInt(components.input_pdetail_ccgroupvalue.val());
                }

                var obj = {
                    id: analysisParameterId,
                    controlChartGroupingNumber: number,
                    distributionChartGroupingNumber: distributionChartGroupingNumber
                };

                var arr = new Array();
                arr.push(obj);

                that.submitRadio("CC", number, arr, "project/updataDcGroupNumber");

            });
        },
        addPSA: function (id) {
            //if (id == null || id == "") {
            //    components.input_pdetail_projectColumn.parent().removeClass("state-success");
            //    components.input_pdetail_projectColumn.parent().addClass("state-error");
            //    document.getElementById("add-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("VALIDATE_ATTRIBUTE_PROJECT") + "</font>";
            //    return;
            //} else {
            //    components.input_pdetail_projectColumn.parent().removeClass("state-error");
            //    components.input_pdetail_projectColumn.parent().addClass("state-success");
            //    document.getElementById("add-label").innerHTML = "<font><em></em></font>";
            //}

            var attributeValue = components.input_pdetail_projectColumn.val();
            var column = document.getElementById('dt_psa');
            var line = column.rows.length;
            var a;
            for (var j = 1; j < line; j++) {

                var cells0 = column.rows[j].cells[1].innerHTML;
                var cells1 = column.rows[j].cells[2].innerHTML;
                if ($.trim(attributeValue) == $.trim(cells1)) {
                    a = false;
                    break;
                }
                else {
                    if ($.trim(attributeValue) == $.trim(cells0)) {
                        a = false;
                        break;
                    } else
                        a = true;
                }
            }
            if ($.trim(attributeValue) != "") {
                components.input_pdetail_projectColumn.parent().removeClass("state-error");
                components.input_pdetail_projectColumn.parent().addClass("state-success");
                document.getElementById("add-label").innerHTML = "<font><em></em></font>";
            } else {
                components.input_pdetail_projectColumn.parent().removeClass("state-success");
                components.input_pdetail_projectColumn.parent().addClass("state-error");
                document.getElementById("add-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("DATAIMPORT_ATTRIBUTE_NAME") + "</font>";
                return;
            }

            if (a == true) {
                components.input_pdetail_projectColumn.parent().removeClass("state-error");
                components.input_pdetail_projectColumn.parent().addClass("state-success");
                document.getElementById("add-label").innerHTML = "<font><em></em></font>";

                var projectObj = {
                    id: components.input_pid.val()
                };
                var obj = {
                    name: $.trim(attributeValue),
                    value: $.trim(attributeValue),
                    isDefault: false,
                    isShow: true,
                    project: projectObj
                };
                var array = new Array();
                array.push(obj);

                $.ajax({
                    url: "psAttribute/addAttribute",
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(array),
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 1) {
                            msgBox.successBox({
                                title: $.i18n.prop("MESSAGEBOX_TITLE_TIPS"),
                                content: $.i18n.prop("PROJECT_SAVE_SUCCESS")
                            });
                        }
                        if (data.code == 0) {
                            if (data.message == "EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS") {
                                msgBox.errorBox("EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS", "PSA_VALUE");
                            } else {
                                msgBox.errorBox(msg);
                            }
                        }
                        components.tbl_psa.DataTable().draw();
                    },
                    error: function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                });

            } else {
                components.input_pdetail_projectColumn.parent().removeClass("state-success");
                components.input_pdetail_projectColumn.parent().addClass("state-error");
                document.getElementById("add-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop('EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS', $.i18n.prop('PROJECT_COLUMN')) + "</font>";
            }
        },
        deletePSA: function (id) {
            msgBox.show({
                title: $.i18n.prop('MESSAGEBOX_CONFIRM_TITLE'),
                content: "" + $.i18n.prop("PSA_DELETE_SUBMIT") + " <p class='text-align-right'>" +
                "<button type='submit' class='btn btn-primary btn-sm deletepsa" + id + "'>" + $.i18n.prop("GLOBAL_BUTTON_YES") + "</button> " +
                "<a href='javascript:void(0);' class='btn btn-danger btn-sm'>" + $.i18n.prop("GLOBAL_BUTTON_NO") + "</a></p>",
                type: 'normal',
                timeout: false,
                clean: true
            });
            $('#divSmallBoxes').find('.deletepsa' + id).unbind('click').on('click', function (e) {
                e.preventDefault();
                that.psaReDrawTable(id);
            });
        },
        psaReDrawTable: function (id) {
            $.ajax({
                "url": "project/deletePSA/" + id,
                "type": "POST",
                "success": function (d) {
                    if (d.code == 0) {
                        msgBox.errorBox(d.message);
                        return false;
                    }
                    msgBox.successBox({
                        content: $.i18n.prop('GLOBAL_DELETE_SUCCESS', $.i18n.prop('PSA_Attribute'))
                    });

                    components.tbl_psa.DataTable().draw();
                },
                "error": function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        submitRadio: function (selector, parameter, arr, url) {
            if (selector == "DC") {
                if (parameter != undefined) {
                    var $validator = components.radio_pdetail_form1.validate({
                        rules: {
                            analysisName: {
                                required: true,
                                positiveinteger: true
                            }
                        },
                        messages: {
                            analysisName: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('PROJECT_GROUP_NUMBER'))
                            }
                        }
                    });

                    var $valid = components.radio_pdetail_form1.valid();
                    if (!$valid) {
                        $validator.focusInvalid();
                        return false;
                    }
                }
            }

            if (selector == "CC") {
                if (parameter != undefined) {
                    var $validator1 = components.radio_pdetail_form2.validate({
                        rules: {
                            analysisNameCC: {
                                required: true,
                                positiveinteger: true
                            }
                        },
                        messages: {
                            analysisNameCC: {
                                required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('PROJECT_GROUP_NUMBER')),
                                positiveinteger: $.i18n.prop("MESSAGE_VALIDATE_POSITIVE", $.i18n.prop("GROUP_LIMIT"))
                            }
                        }
                    });
                    var $valid1 = components.radio_pdetail_form2.valid();
                    if (!$valid1) {
                        $validator1.focusInvalid();
                        return false;
                    }
                }
            }

            $.ajax({
                url: url,
                type: 'POST',
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify(arr),
                success: function (data) {
                    if (data.code == 1) {
                        msgBox.successBox({
                            title: $.i18n.prop("MESSAGEBOX_TITLE_TIPS"),
                            content: $.i18n.prop("PROJECT_SAVE_SUCCESS")
                        });
                    }
                    if (data.code == 0) {
                        msgBox.errorBox("EXCEPTION_GLOBAL_PARAMETER_INPUTINVALID");
                    }
                },
                error: function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        submitAjaxData: function (url, params) {
            $.ajax({
                url: url,
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(params),
                dataType: "json",
                success: function (data) {
                    if (data.code == 1) {
                        msgBox.successBox({
                            title: $.i18n.prop("MESSAGEBOX_TITLE_TIPS"),
                            content: $.i18n.prop("PROJECT_SAVE_SUCCESS")
                        });
                        appLocalStorage.setLocal("ispc.search.project.code." + global.getUserId(), components.input_pdetail_code.val().trim());
                    }
                    if (data.code == 0) {
                        if (data.message == "EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS") {
                            msgBox.errorBox("EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS", "GLOBAL_VALUE");
                        } else {
                            msgBox.errorBox("EXCEPTION_GLOBAL_PARAMETER_INPUTINVALID");
                        }
                    }
                    //components.tbl_psa.DataTable().draw();
                },
                error: function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },

        initGrrSetting:function () {
            var rules = components.txt_project_psgrr_rules.val();
            var defaultModelValue = components.txt_project_psgrr_defaultModelValue.val();
            rules = rules.substring(1, rules.length-1);
            defaultModelValue = defaultModelValue.substring(1, defaultModelValue.length-1);
            var ruleArr = rules.split(",");
            var defaultModelArr = defaultModelValue.split(",");
            components.txt_project_grr_part.val(defaultModelArr[0]);
            components.txt_project_grr_operator.val(defaultModelArr[1]);
            components.txt_project_grr_trial.val(defaultModelArr[2]);
            components.txt_project_grr_Excellent.val(ruleArr[0]);
            components.txt_project_grr_Adequate.val(ruleArr[1]);
            components.txt_project_grr_Marginal.val(ruleArr[2]);

            components.slt_project_grr_type.select2({
                id: function (rs) {
                    return rs.id;
                },
                // allowClear: true,
                data: function () {
                    return {
                        results: [{id: "NORMAL", text: "Appraisers - Trial - Part"},
                            {id: "SLOT", text: "Slot - Trial - Part"}]
                    };
                },
                formatResult: function (d) {
                    var itemFmt = "<span>" + d.text == null ? '' : d.text + "</span>";
                    return itemFmt;
                },
                formatSelection: function (d) {
                    return d.text == null ? '' : d.text;
                },
                formatMatches: function () {
                },
                formatNoMatches: function () {
                    return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                },
                escapeMarkup: function (m) {
                    return m;
                }
            });
            components.slt_project_grr_type.select2('val', components.txt_project_psgrr_model.val());

            components.slt_project_grr_sigma.select2({
                id: function (rs) {
                    return rs.id;
                },
                // allowClear: true,
                data: function () {
                    return {
                        results: [{id: "6.0", text: "6.0"},
                            {id: "5.15", text: "5.15"}]
                    };
                },
                formatResult: function (d) {
                    var itemFmt = "<span>" + d.text == null ? '' : d.text + "</span>";
                    return itemFmt;
                },
                formatSelection: function (d) {
                    return d.text == null ? '' : d.text;
                },
                formatMatches: function () {
                },
                formatNoMatches: function () {
                    return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                },
                escapeMarkup: function (m) {
                    return m;
                }
            });
            components.slt_project_grr_sigma.select2('val', components.txt_project_psgrr_sigma.val());

            var params = {
                search_projectId: components.input_pid.val()
            };
            $.ajax({
                url: "analysis/grr/getGrrItem",
                type: "POST",
                dataType: "json",
                data: params,
                success: function (data) {
                    if (data.code == 1) {
                        if (data.body.length > 0) {
                            components.slt_project_grr_type.prop("disabled", true);
                            components.slt_project_grr_sigma.prop("disabled", true);
                        }
                    }
                },
                error: function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        getGrrSettingParams: function () {
            var value = new Array();
            value.push(parseFloat(components.txt_project_grr_part.val()));
            value.push(parseFloat(components.txt_project_grr_operator.val()));
            value.push(parseFloat(components.txt_project_grr_trial.val()));

            var ruleValue = new Array();
            ruleValue.push(parseFloat(components.txt_project_grr_Excellent.val()));
            ruleValue.push(parseFloat(components.txt_project_grr_Adequate.val()));
            ruleValue.push(parseFloat(components.txt_project_grr_Marginal.val()));

            var params = {
                id: components.txt_project_psgrr_id.val(),
                model: components.slt_project_grr_type.select2("val"),
                sigma: components.slt_project_grr_sigma.select2("val"),
                defaultModelValue:JSON.stringify(value),
                projectId: components.input_pid.val(),
                rule: JSON.stringify(ruleValue)
            };

            var arr = new Array();
            arr.push(params);
            return arr;
        },
        submitGrrSetting: function () {
            components.btn_project_grr_save.click(function () {
                var excellentValue = components.txt_project_grr_Excellent.val();
                var adequateValue = components.txt_project_grr_Adequate.val();
                var marginalValue = components.txt_project_grr_Marginal.val();
                var adequateParam = {
                    beforeValue: excellentValue,
                    afterValue: marginalValue
                };
                var $validator = components.form_grr_setting.validate({
                    rules: {
                        appraisers: {
                            required: true,
                            positiveinteger: true
                        },
                        trials: {
                            required: true,
                            positiveinteger: true
                        },
                        parts: {
                            required: true,
                            positiveinteger: true
                        },
                        excellent: {
                            required: true,
                            positiveinteger: true,
                            excellentRule: adequateValue
                        },
                        adequate: {
                            required: true,
                            positiveinteger: true,
                            betweenRule: adequateParam
                        },
                        marginal: {
                            required: true,
                            positiveinteger: true,
                            marginalRule: adequateValue
                        }
                    },
                    messages: {
                        appraisers: {
                            required: $.i18n.prop('VALIDATE_REQUIRED', "appraisers"),
                        },
                        trials: {
                            required: $.i18n.prop('VALIDATE_REQUIRED', "trials"),
                        },
                        parts: {
                            required: $.i18n.prop('VALIDATE_REQUIRED', "parts"),
                        },
                        excellent: {
                            required: $.i18n.prop('VALIDATE_REQUIRED', "excellent"),
                        },
                        adequate: {
                            required: $.i18n.prop('VALIDATE_REQUIRED', "adequate"),
                        },
                        marginal: {
                            required: $.i18n.prop('VALIDATE_REQUIRED', "marginal"),
                        }
                    },
                });
                $validator.settings.rules.excellent.excellentRule = adequateValue;
                $validator.settings.rules.adequate.betweenRule = adequateParam;
                $validator.settings.rules.marginal.marginalRule = adequateValue;
                var $valid = components.form_grr_setting.valid();
                if (!$valid) {
                    $validator.focusInvalid();
                    return false;
                }
                $.ajax({
                    url: "project/updataPSGRR",
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json",
                    data: JSON.stringify(that.getGrrSettingParams()),
                    success: function (data) {
                        if (data.code == 1) {
                            msgBox.successBox({
                                title: $.i18n.prop("MESSAGEBOX_TITLE_TIPS"),
                                content: $.i18n.prop("PROJECT_SAVE_SUCCESS")
                            });
                            appLocalStorage.setLocal("ispc.search.project.code." + global.getUserId(), components.input_pdetail_code.val().trim());
                        }
                        if (data.code == 0) {
                            msgBox.errorBox("EXCEPTION_GLOBAL_PARAMETER_INPUTINVALID");
                        }
                    },
                    error: function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                });
            });
        }
    }
});